package pl.google_wave_blog.plcensorbot;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class BadWords {

	private List<String> badWordsList;

	public void getWordsList() {
		badWordsList = new ArrayList<String>();
		// Method from GPLv3 project Censorboty - http://censorboty.appspot.com
		try {

			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = builder
					.parse("http://plcensorbot.appspot.com/words.xml");
			NodeList words = doc.getElementsByTagName("word");
			for (int i = 0; i < words.getLength(); i++) {
				badWordsList.add(words.item(i).getTextContent());
			}

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String censor(String text) {
		Iterator<String> it = badWordsList.iterator();
		while (it.hasNext()) {
			text = text.replaceAll(it.next(), "[CENZURA]");
		} 
		return text;
	}
}
